<?php

namespace app\admin\model;

use think\facade\Db;

class Contentmodel extends Commonmodel {

    protected $userTable;
    protected $videoTable;
    protected $croomTable;
    protected $detailTable;
    protected $courseTable;
    protected $classifyTable;

    public function __construct(array $data = [])
    {
        $this->table = 'zhjs_content';
        $this->pk = 'id';
        parent::__construct($data);
        $this->userTable = 'zhjs_user';
        $this->croomTable = 'zhjs_classroom';
        $this->detailTable = 'zhjs_content_detail';
        $this->videoTable = 'zhjs_content_video';
        $this->courseTable = 'zhjs_content_course';
        $this->classifyTable = 'zhjs_content_classify';
    }

    /**
     * 查询文章
     * @param string $type        类型分类(1:图文;2:流媒体;5:课件;6:课程;7:策略)
     * @param null $where
     * @param null $pageParam
     * @param int $num
     * @return bool
     */
    public function findAll($type = '1', $where = null, $pageParam = null, $whereExp = null, $num = 15){
        $whereData = [['c.is_delete' , '=', 1]];
        $paginate = ['list_rows'=>$num];

        if($where)  $whereData = array_merge($where, $whereData);
        if(!$whereExp)  $whereExp = '1=1';
        if($pageParam = array_splice($pageParam, 1))  $paginate = array_merge($paginate, ['query'=>$pageParam]);

        $select = 'c.id, c.title, c.uid, c.cid, c.crid, c.title, c.create_date, c.examine_status, c.reason, u.username, c.status, cr.name as crname, cr.status as crstatus, cf.name as cfname';
        switch($type){
            case 2:
                $select .= ', o.start_time, o.end_time';
                $whereData[] = ['c.type', 'in', '2, 3, 4'];
                $joinArr = [$this->videoTable=>'o'];
                break;

            case 3:
                $select .= ', o.duration';
                $whereData[] = ['c.type', '=', 5];
                $joinArr = [$this->detailTable=>'o'];
                break;

            default:
                $whereData[] = ['c.type', '=', $type];
                $joinArr = [$this->detailTable=>'o'];
                break;
        }

        $data = self::db()
            ->alias('c')
            ->leftJoin([$this->userTable=>'u'],'c.uid=u.id')
            ->leftJoin([$this->croomTable=>'cr'],'c.crid=cr.id')
            ->leftJoin([$this->classifyTable=>'cf'],'c.cid=cf.id')
            ->leftJoin($joinArr,'o.id=c.id')
            ->field($select)
            ->where($whereData)
            ->whereExp('', $whereExp)
            ->order(['c.id'=>'desc'])
            ->paginate($paginate);

        if(!$data)  return false;

        $list['page'] = $data->render();
        $dataArr = $data->toArray();
        $list['data'] = $dataArr['data'];

        return $list;
    }

    public function saveInfo($dataArr, $otherArr, $courseArr = null, $id = null){
        if(!$dataArr || !$otherArr)  return false;

        if(!$id){
            $dataArr['uid'] = session('adminUserInfo.uid');
        }

        Db::startTrans();
        try {
            if($id){
                if($otherArr['video_api_id'] || $otherArr['url']){
                    $otherTbale = $this->videoTable;
                }else{
                    $otherTbale = $this->detailTable;
                }
                $dataArr['examine_status'] = 1;         //内容被修改后，重新进入审核状态待审
                Db::table($this->table)->where(['id'=>$id])->update($dataArr);
                Db::table($otherTbale)->where(['id'=>$id])->save($otherArr);
                if($courseArr){
                    Db::table($this->courseTable)->where(['id'=>$id])->delete();
                    Db::table($this->courseTable)->insertAll($this->getCourseArr($courseArr, $id));
                }
            }else {
                if($otherArr['video_api_id'] || $otherArr['url']){
                    $otherTbale = $this->videoTable;
                }else{
                    $otherTbale = $this->detailTable;
                }
                Db::table($this->table)->save($dataArr);
                $id = $otherArr['id'] = Db::table($this->table)->getLastInsID();
                Db::table($otherTbale)->save($otherArr);
                if($courseArr)  Db::table($this->courseTable)->insertAll($this->getCourseArr($courseArr, $id));
            }
            Db::commit();
            return $id;
        } catch (\Exception $e) {
            trace('(saveInfo)保存\修改失败，添加内容为：' . json_encode($dataArr) . '失败原因：' . $e->getMessage(), 'error');
            Db::rollback();
            return false;
        }
    }

    /**
     * 组合课程数据
     * @param $courseArr
     * @param $id
     * @return array|bool
     */
    public function getCourseArr($courseArr, $id){
        if(!$courseArr || !$id)  return false;

        $newCourseArr = [];
        foreach($courseArr as $k=>$v){
            $newCourseArr[] = [
                'id'    => $id,
                'cwid'  => $k,
                'order' => $v['order']
            ];
        }

        return $newCourseArr;
    }

    /**
     * 查询文章内容
     * @param string $select
     * @param null $id
     * @param bool $is_detail
     * @param null $where
     * @return bool
     */
    public function findDetaiById($select=  "*", $id = null, $is_detail = true, $where = null){
        if(!$id && !$where)  return false;

        if($is_detail){
            $otherTbale = $this->detailTable;
        }else{
            $otherTbale = $this->videoTable;
        }
        $select = 'o.*, c.*';

        $where = $where ? array_merge($where, ['c.id'=>$id]) : ['c.id'=>$id];
        $info = self::db()
            ->alias('c')
            ->leftJoin([$otherTbale=>'o'],'o.id=c.id')
            ->field($select)
            ->where($where)
            ->find();

        $info = $info ? $info->toArray() : '';

        if(!$info)  return false;

        if($info['type'] == 6){
            $info['course'] = self::db()
                ->alias('c')
                ->leftJoin ([$this->courseTable=>'w'],'w.id=c.id')
                ->leftJoin ([$this->table=>'ct'],'w.cwid=ct.id')
                ->field('w.cwid, ct.title, w.order')
                ->where(['c.id'=>$id])
                ->order(['w.order'=>'desc', 'ct.examine_status'=>9, 'ct.status'=>1])
                ->select()->toArray();
            if($info['course']){
                foreach($info['course'] as $cVal){
                    $idsArr[] = $cVal['cwid'];
                }
                $info['ids'] = implode(',', $idsArr);
            }
        }
        return $info;
    }

    //根据课件和议程类型选择课件
    public function findCourseListBycid($cid, $ctype){
        if(!$cid || !$ctype)  return false;
        $this->detailTable = 'zhjs_content_detail';
        $this->videoTable = 'zhjs_content_video';
        $this->courseTable = 'zhjs_content_course';
        $listObj = Db::table($this->courseTable)
            ->alias('cc')
            ->leftJoin([$this->table=>'c'], 'cc.cwid=c.id')
            ->leftJoin([$this->detailTable=>'d'], 'd.id=c.id')
            ->field('c.id, c.title')
            ->where(['c.status'=>1, 'cc.id'=>$cid, 'd.ctype'=>$ctype, 'c.is_delete'=>1, 'c.examine_status'=>9])
            ->select();

        if(!$listObj)  return false;
        $list = $listObj->toArray();

        return $list;
    }

}

?>